package com.xinjiang.electricpower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.ruoyi.common.core.utils.StringUtils;
import com.xinjiang.electricpower.domain.DTO.WorkOrderEarlyWarningDTO;
import com.xinjiang.electricpower.domain.XjOrderGeneral;
import com.xinjiang.electricpower.domain.vo.*;
import com.xinjiang.electricpower.enums.ElectricPowerEnums;
import com.xinjiang.electricpower.mapper.XjOrderGeneralMapper;
import com.xinjiang.electricpower.service.IUserAuthService;
import com.xinjiang.electricpower.service.IWorkOrderWarningService;
import com.xinjiang.electricpower.service.IXjOrderConfigService;
import com.xinjiang.electricpower.service.IXjOrderGeneralService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;

/**
 * @author feizhao
 * @date 2022/11/17
 * @apiNote
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkOrderWarningServiceImpl extends ServiceImpl<XjOrderGeneralMapper, XjOrderGeneral> implements IWorkOrderWarningService {

    @Autowired
    private IUserAuthService iUserAuthService;

    private final IXjOrderGeneralService xjOrderGeneralService;


    private final IXjOrderConfigService xjOrderConfigService;

    DateTimeFormatter formatHour = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");
    ZoneId zoneId = ZoneId.systemDefault();
    DateTimeFormatter formatMonth = DateTimeFormatter.ofPattern("yyyy-MM");

    @Override
    public List<EventProcessingVO> selectGdWarningTypesCount(WorkOrderEarlyWarningDTO workOrderEarlyWarningDTO) {
        QueryWrapper<WorkOrderEarlyWarningDTO> queryWrapper = new QueryWrapper<WorkOrderEarlyWarningDTO>();
        String priority = "atyx.processing_status";
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        queryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"atyx.org_no",authStr.getOrgNo());
        queryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"atyx.cons_no",authStr.getConsNo());
        queryWrapper.ne(priority, ElectricPowerEnums.ORDER_PRIORITY_WARNING.getValue());
        //queryWrapper.le(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getTimeGranularityHour()), "UNIX_TIMESTAMP(DATE_FORMAT(atyx.tj_time,'%Y-%m-%d %H'))", StringUtils.isNotEmpty(format) ? LocalDateTime.parse(Objects.requireNonNull(format), formatHour).atZone(zoneId).toInstant().toEpochMilli() : null);
        //queryWrapper.eq(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getTimeGranularityMonth()), "DATE_FORMAT(atyx.tj_time,'%Y-%m')", format1);
        queryWrapper.ge(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getAppYjStartTime()), "atyx.handle_time", workOrderEarlyWarningDTO.getAppYjStartTime());
        queryWrapper.le(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getAppYjEndTime()), "atyx.handle_time", ObjectUtils.isEmpty(workOrderEarlyWarningDTO.getAppYjEndTime()) ? workOrderEarlyWarningDTO.getAppYjEndTime() : workOrderEarlyWarningDTO.getAppYjEndTime().plusDays(1L));
        queryWrapper.groupBy(priority, "atyx.app_yjdj");
        return baseMapper.selectEventProcessingVO(queryWrapper);
    }

    /**
     * 自定义分页
     *
     * @param page                     分页对象
     * @param workOrderEarlyWarningDTO 工单预警DTO类
     * @return PageInfo<MyEarlyWarningVO> 返回工单预警实体类待处理分页信息
     */
    @Override
    public PageInfo<MyEarlyWarningVO> selectMyEarlyWarningPage(PageDTO<MyEarlyWarningVO> page, WorkOrderEarlyWarningDTO workOrderEarlyWarningDTO) {
        QueryWrapper<MyEarlyWarningVO> wrapper = new QueryWrapper<>();
        String[] split = null;
        if (ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getPriority())) {
            split = workOrderEarlyWarningDTO.getPriority().split(",");
        }
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        wrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"atyx.org_no",authStr.getOrgNo());
        wrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"atyx.cons_no",authStr.getConsNo());
        wrapper.like(StringUtils.hasText(workOrderEarlyWarningDTO.getAppNo()), "atyx.app_no", workOrderEarlyWarningDTO.getAppNo());
        //wrapper.eq(StringUtils.hasText(workOrderEarlyWarningDTO.getTgId()), "xog.tg_id", workOrderEarlyWarningDTO.getTgId());
        wrapper.eq(StringUtils.hasText(workOrderEarlyWarningDTO.getProcessingStatus()), "atyx.processing_status", workOrderEarlyWarningDTO.getProcessingStatus());
        //wrapper.like(StringUtils.hasText(workOrderEarlyWarningDTO.getTgName()), "xog.tg_name", workOrderEarlyWarningDTO.getTgName());
        wrapper.like(StringUtils.hasText(workOrderEarlyWarningDTO.getAssignerName()), "atyx.assigner_name", workOrderEarlyWarningDTO.getAssigner());
        wrapper.in(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getPriority()), "atyx.app_yjdj", ObjectUtils.isNotEmpty(split) ? Arrays.asList(split) : null);
        wrapper.like(StringUtils.hasText(workOrderEarlyWarningDTO.getAppYjmc()), "atyx.app_yjmc", workOrderEarlyWarningDTO.getAppYjmc());
        wrapper.eq(StringUtils.hasText(workOrderEarlyWarningDTO.getAppYjxl()), "atyx.app_yjxl", workOrderEarlyWarningDTO.getAppYjxl());
        wrapper.ge(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getAppYjStartTime()), "atyx.handle_time", workOrderEarlyWarningDTO.getAppYjStartTime());
        wrapper.le(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getAppYjEndTime()), "atyx.handle_time", ObjectUtils.isEmpty(workOrderEarlyWarningDTO.getAppYjEndTime()) ? workOrderEarlyWarningDTO.getAppYjEndTime() : workOrderEarlyWarningDTO.getAppYjEndTime().plusDays(1L));
        //wrapper.le(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getTimeGranularityHour()), "UNIX_TIMESTAMP(DATE_FORMAT(atyx.tj_time,'%Y-%m-%d %H'))", StringUtils.isNotEmpty(format) ? LocalDateTime.parse(Objects.requireNonNull(format), formatHour).atZone(zoneId).toInstant().toEpochMilli() : null);
        //wrapper.eq(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getTimeGranularityMonth()), "DATE_FORMAT(atyx.tj_time,'%Y-%m')", format1);
        wrapper.orderByDesc("atyx.app_yjdj");
        //开启分页功能
        PageMethod.startPage(Integer.parseInt(String.valueOf(page.getCurrent())), Integer.parseInt(String.valueOf(page.getSize())));
        List<MyEarlyWarningVO> myEarlyWarnings = baseMapper.findMyEarlyWarnings(wrapper);
        myEarlyWarnings.forEach(item -> {
            item.setSinceNow(this.daysBetweenDateTime(item.getTjTime()));
            item.setSystemTime(LocalDateTime.now());
        });
        return new PageInfo<MyEarlyWarningVO>(myEarlyWarnings);
    }

    /**
     * 查看详情
     *
     * @param id 工单id
     * @return MyEarlyWarningVO 预警工单详情VO类
     */
    @Override
    public MyEarlyWarningVO selectMyEarlyWarningDetail(String id) {
        QueryWrapper<MyEarlyWarningVO> wrapper = new QueryWrapper<>();
        wrapper.eq("atyx.id", id);
        MyEarlyWarningVO myEarlyWarning = baseMapper.findMyEarlyWarning(wrapper);
//        if (ObjectUtils.isNotEmpty(myEarlyWarning.getAppYjdm())) {
//            QueryWrapper<MyEarlyWarningVO> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("id", myEarlyWarning.getAppYjdm());
//            WarningContentVO warningContentVO = baseMapper.selectWarningContent(queryWrapper);
//            myEarlyWarning.setYjContent(warningContentVO.getWarningContent());
//        } else {
//
//            myEarlyWarning.setYjContent(null);
//        }
        return myEarlyWarning;
    }

    /**
     * 工单预警按照各个类型汇总待办工单
     *
     * @return List<WorkOrderPoolSummaryVO> 返回汇总数据
     */
    @Override
    public List<WorkOrderPoolSummaryVO> getXjOrderGeneralByStatus(WorkOrderEarlyWarningDTO workOrderEarlyWarningDTO) {
        QueryWrapper<WorkOrderPoolSummaryVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getAppYjStartTime()), "atyx.tj_time", workOrderEarlyWarningDTO.getAppYjStartTime());
        queryWrapper.le(ObjectUtils.isNotEmpty(workOrderEarlyWarningDTO.getAppYjEndTime()), "atyx.tj_time", ObjectUtils.isEmpty(workOrderEarlyWarningDTO.getAppYjEndTime()) ? workOrderEarlyWarningDTO.getAppYjEndTime() : workOrderEarlyWarningDTO.getAppYjEndTime().plusDays(1L));
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        queryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
        queryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        queryWrapper.isNotNull("xog.type");
        queryWrapper.groupBy("xog.type");
        queryWrapper.orderByDesc("num");
        return baseMapper.selectXjOrderGeneralByStatus(queryWrapper);
    }

    /**
     * 查询工单列表无分页
     *
     * @param ids 批量id
     * @return List<XjOrderGeneralVO> 返回工单列表
     */
    @Override
    public List<MyEarlyWarningVO> selectMyEarlyWarnings(String... ids) {
        QueryWrapper<MyEarlyWarningVO> queryWrapper = new QueryWrapper<>();
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        queryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
        queryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        queryWrapper.in("xog.id", Arrays.asList(ids));
        return baseMapper.findMyEarlyWarnings(queryWrapper);
    }

    /**
     * 查询工单列表无分页
     *
     * @param workOrderEarlyWarningDTO 派工单DTO类
     * @return List<MyEarlyWarningVO> 返回预警工单列表
     */
    @Override
    public List<MyEarlyWarningVO> selectMyEarlyWarnings(WorkOrderEarlyWarningDTO workOrderEarlyWarningDTO) {
        QueryWrapper<MyEarlyWarningVO> objectQueryWrapper = new QueryWrapper<>();
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        objectQueryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"atyx.org_no",authStr.getOrgNo());
        objectQueryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"atyx.cons_no",authStr.getConsNo());
        return baseMapper.findMyEarlyWarnings(objectQueryWrapper);
    }

    /**
     * 标记处理
     *
     * @param workOrderEarlyWarningDTO 工单预警DTO类
     * @return boolean 修改状态
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateProcessingMark(WorkOrderEarlyWarningDTO workOrderEarlyWarningDTO) {
        return baseMapper.updateProcessStatus(workOrderEarlyWarningDTO.getId(), Integer.parseInt(workOrderEarlyWarningDTO.getProcessingStatus()));
    }

    /**
     * 计算统计时间与当前时间的距离
     */
    public String daysBetweenDateTime(LocalDateTime localDatetime) {
        long absHour = Math.abs(ChronoUnit.HOURS.between(localDatetime, LocalDateTime.now()) % 24);
        long absMin = Math.abs(ChronoUnit.MINUTES.between(localDatetime, LocalDateTime.now()) % 60);
        long absSec = Math.abs(ChronoUnit.SECONDS.between(localDatetime, LocalDateTime.now()) % 60);
        return absHour + "时" + absMin + "分" + absSec + "秒";
    }

}
